Java syntax
part 22/36 Β· 136.0 KB total
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
similar to functions except they belong to classes. A method has a
return value, a name and usually some parameters initialized when it is
called with some arguments. Similar to C++, methods returning nothing
have return type declared as void. Unlike in C++, methods in Java are
not allowed to have default argument values and methods are usually
overloaded instead.
class Foo {
int bar(int a, int b) {
return (a*2) + b;
}
/* Overloaded method with the same name but different set of arguments
*/
int bar(int a) {
return a*2;
}
}
A method is called using . notation on an object, or in the case of a
static method, also on the name of a class.
Foo foo = new Foo();
int result = foo.bar(7, 2); // Non-static method is called on foo
int finalResult = Math.abs(result); // Static method call
The throws keyword indicates that a method throws an exception. All
checked exceptions must be listed in a comma-separated list.
void openStream() throws IOException, myException { // Indicates that
IOException may be thrown
}
Modifiers
such methods have no body and must be overridden in a subclass unless it
is abstract itself.
β’ static - Makes the method static and accessible without creation of a
class instance. However static methods cannot access non-static members
in the same class.
β’ final - Declares that the method cannot be overridden in a subclass.
β’ native - Indicates that this method is implemented through JNI in
platform-dependent code. Actual implementation happens outside Java
code, and such methods have no body.
β’ strictfp - Declares strict conformance to IEEE 754 in carrying out
floating-point operations.
β’ synchronized - Declares that a thread executing this method must
acquire monitor. For synchronized methods the monitor is the class
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ